<script setup lang="tsx">
import { reactive, ref, watch, onMounted, unref } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElCheckbox } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { loginApi, getTestRoleApi, getAdminRoleApi } from '@/api/login'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { useUserStore } from '@/store/modules/user'
import { BaseButton } from '@/components/Button'
import { Icon } from '@/components/Icon'
// import logo from '@/assets/imgs/logo.png'
// 是否东宝令验证
const showRandom = ref(false)
const { required } = useValidator()

const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const userStore = useUserStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()


const rules = {
  // username: [required()],
  // password: [required()]
}


const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <> 
            <div class="logoImg flex justify-center w-[100%]">
              <img src='/src/assets/login/logo.png'   />
              </div>
            </>
          )
        }
      },
    },
  
  },
  {
    field: 'username',
    // value: 'admin', 
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入系统编号',
      prefixIcon: <Icon icon="svg-icon:orgId" />
    },
  },
  {
    field: 'password',
    // value: 'admin',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入用户名/手机号',
      prefixIcon: <Icon icon="svg-icon:user" />
    },

  },
  {
    field: 'password12',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '输入登录密码',
      prefixIcon: <Icon icon="svg-icon:password" />,
      // 按下enter键触发登录
      onKeydown: (_e: any) => {
        if (_e.key === 'Enter') {
          _e.stopPropagation() // 阻止事件冒泡
          signIn()
        }
      }
    },
    formItemProps: {
      // style:{
      //   marginBottom:'16px',
      //   height:'46px'
      // }
    },
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%] remeber">
                <ElCheckbox v-model={remember.value} label="记住账号" size="small" />
              </div>
            </>
          )
        }
      },

    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="loginBtn w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                 登录
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }
  }
])
const Verification = reactive<FormSchema[]>([


  {
    field: 'otherIcon',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <> 
            <div class="logoImg flex justify-center w-[100%]">
              <img src='/src/assets/login/logo.png'   />
              </div>
            </>
          )
        }
      },
    },
  
  },
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <div class="mfa font-bold text-center w-[100%]">MFA认证</div>
        }
      }
    }
  },
  {
    field: 'otherIcon',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="safe flex  justify-center w-[100%] " >
                <img src="/src/assets/login/safe.png" alt="" />
                <span class="text-14px text-center">
                  账号保护已开启，请根据提示完成以下操作
                </span>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'otherIcon',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex  justify-center w-[100%] photo">
                <img  src="/src/assets/login/photo.png" alt="" />
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <div class="tip text-center w-[100%]">请打开微信 [東宝令] 小程序，输入6位动态码</div>
        }
      }
    }
  },
  {
    field: 'userRandom',

    // value: 'admin',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '输入动态码',
      prefixIcon: <Icon icon="ph:file-text" />
    }
  },


  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class=" loginBtn w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={checkIn}
                >
                  进入运营商平台
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }

  },
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <div class="w-[100%] text-center text">如果不能提供MFA验证码，请联系管理员!</div>
        }
      }
    }
  }
  
])


const remember = ref(userStore.getRememberMe)

const initLoginInfo = () => {
  const loginInfo = userStore.getLoginInfo
  if (loginInfo) {
    const { username, password } = loginInfo
    setValues({ username, password })
  }
}
onMounted(() => {
  initLoginInfo()
})

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose, setValues } = formMethods

const loading = ref(false)


const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 登录
const signIn = async () => {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<UserType>()

      try {
        // const res = await '/mock/user/login'.post(formData)
        // console.log(res,'res====>');
        
       

        showRandom.value = !showRandom.value //显示输入动态码框
      } finally {
        loading.value = false
      }
    }
  })
}
const checkIn = async () => {
  const formRef = await getElFormExpose()

  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      // const formData = await getFormData<UserCheckType>()
        const formData = await getFormData<UserType>()
      // const userData = {
      //   userRandom: '' + formData.userRandom,
      //   _ip: ''
      // }
      try {
        const res = await loginApi(formData)

if (res) {
  // 是否记住我
  if (unref(remember)) {
    userStore.setLoginInfo({
      username: formData.username,
      password: formData.password
    })
  } else {
    userStore.setLoginInfo(undefined)
  }
  userStore.setRememberMe(unref(remember))
  userStore.setUserInfo(res.data)
  // 是否使用动态路由
  if (appStore.getDynamicRouter) {
    getRole()
  } else {
    await permissionStore.generateRoutes('static').catch(() => {})
    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    push({ path: redirect.value || permissionStore.addRouters[0].path })
  }
}

      } finally {
        loading.value = false
      }
    }
  })
}
// 获取角色信息
const getRole = async () => {
  const formData = await getFormData<UserType>()
  const params = {
    roleName: formData.username
  }
  const res =
    appStore.getDynamicRouter && appStore.getServerDynamicRouter
      ? await getAdminRoleApi(params)
      : await getTestRoleApi(params)
  if (res) {
    const routers = res.data || []
    userStore.setRoleRouters(routers)
    appStore.getDynamicRouter && appStore.getServerDynamicRouter
      ? await permissionStore.generateRoutes('server', routers).catch(() => {})
      : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {})

    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    push({ path: redirect.value || permissionStore.addRouters[0].path })
  }
}

</script>

<template>
    <Form
    :schema="showRandom ? Verification : schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    :class="showRandom? 'check-form':'logon-form'"
    class=" dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="formRegister"

  />
  <!-- <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="logon-form dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="formRegister"

  /> -->
</template>

<style lang="less" scoped>

</style>
